/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
struct ListNode {
    int val;
    ListNode *next;

    ListNode(int x) : val(x), next() {}
};

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        int la = 0, lb = 0;
        ListNode *tmp_a = headA, *tmp_b = headB;
        while (tmp_a) {
            tmp_a = tmp_a->next;
            la++;
        }
        while (tmp_b) {
            tmp_b = tmp_b->next;
            lb++;
        }
        ListNode *pa = headA, *pb = headB;
        if (la > lb) {
            int minus = la - lb;
            while (minus--) {
                headA = headA->next;
            }
        }
        if (lb > la) {
            int minus = lb - la;
            while (minus--) {
                headB = headB->next;
            }
        }
        while (headA != headB) {
            headA = headA->next;
            headB = headB->next;
        }
        return headA;
    }
};